import { _decorator, Component, Node, Scene } from 'cc';
import { DEBUG_REPAIR_MISSING_SCRIPTS } from '../shared';

const { ccclass } = _decorator;

function getNodePath(n: Node): string {
  const names: string[] = [];
  let cur: Node | null = n;
  while (cur) {
    names.push(cur.name);
    cur = cur.parent as any;
  }
  return names.reverse().join('/');
}

@ccclass('RepairMissingScripts')
export class RepairMissingScripts extends Component {
  onLoad() {
    if (!DEBUG_REPAIR_MISSING_SCRIPTS) return;
    const scene = (this.node.scene as unknown) as Scene | null;
    if (!scene) return;
    const root = scene as unknown as Node;
    const stack: Node[] = [root];
    let count = 0;
    while (stack.length) {
      const node = stack.pop()!;
      // push children
      for (const ch of node.children) stack.push(ch);
      const comps: any[] = (node as any)._components ?? [];
      for (let idx = 0; idx < comps.length; idx++) {
        const c = comps[idx];
        const ctorName = (c && c.constructor && c.constructor.name) || '';
        const clsName = (c && (c.__classname__ || c.name)) || '';
        const looksMissing = !c || /Missing/i.test(ctorName) || /Missing/i.test(clsName);
        if (looksMissing) {
          count++;
          const path = getNodePath(node);
          if (typeof console !== 'undefined' && console.warn) {
            console.warn('[REPAIR] Missing Script at', path, 'index=', idx, 'ctor=', ctorName || clsName);
          }
        }
      }
    }
    if (count === 0 && typeof console !== 'undefined' && console.debug) {
      console.debug('[REPAIR] No missing scripts detected');
    }
  }
}

export default RepairMissingScripts;

